-module(db).
-export([new/0, destroy/1, write/3, delete/2, read/2, match/2]).

-include("db.hrl").

-ifdef(debug).
-define(DBG(Str, Args), io:format(Str, Args)).
-else.
-define(DBG(Str, Args), ok).
-endif.

new() ->
    ?DBG("create a db~n", []),
    [].

destroy(_) ->
    ?DBG("destroy the db~n", []),
    [].

write(Key, Element, Db) ->
    ?DBG("write db~n", []),
    Data = #data{key=Key, element=Element},
    [Data | Db].

delete(Key, Db) ->
    ?DBG("delete db~n", []),
    delete_help(Key, Db).

delete_help(_Key, []) ->
    [];
delete_help(Key, [#data{key=Key} | Rest]) ->
    delete_help(Key, Rest);
delete_help(Key, [Other | Rest]) ->
    [Other | delete_help(Key, Rest)].

read(Key, Db) ->
    ?DBG("read db~n", []),
    read_help(Key, Db).

read_help(_Key, []) ->
    {error, instance};
read_help(Key, [#data{key=Key, element=Element} | _Rest]) ->
    {ok, Element};
read_help(Key, [_Other | Rest]) ->
    read_help(Key, Rest).

match(Element, Db) ->
    ?DBG("match db~n", []),
    match_help(Element, Db).

match_help(_Element, []) ->
    [];
match_help(Element, [#data{key=Key,element=Element} | Rest]) ->
    [Key | match_help(Element, Rest)];
match_help(Element, [_Other | Rest]) ->
    match_help(Element, Rest).
